package middle;

import java.util.Stack;

public class Solution_173 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(7);
        root.left = new TreeNode(3);
        root.right = new TreeNode(15);
        root.right.left = new TreeNode(9);
        root.right.right = new TreeNode(20);
        BSTIterator model = new BSTIterator(root);
        System.out.println(model.next());
        System.out.println(model.next());
        System.out.println(model.hasNext());
        System.out.println(model.next());
        System.out.println(model.hasNext());
        System.out.println(model.next());
        System.out.println(model.hasNext());
        System.out.println(model.next());
        System.out.println(model.hasNext());
    }

    static class BSTIterator {
        private Stack<TreeNode> stack;

        public BSTIterator(TreeNode root) {
            stack = new Stack<>();
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
        }

        public int next() {
            TreeNode pop = stack.pop();
            TreeNode node = pop.right;
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
            return pop.val;
        }

        public boolean hasNext() {
            return !stack.empty();
        }
    }

    static class TreeNode {

        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
